package com.example.audit.codesec_client.whitelistDemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.*;
import java.util.regex.Pattern;

public class ArgumentDemo {

    @RequestMapping("/jdbc/vuln")
    public String jdbc_sqli_vul(@RequestParam("username") String username, @RequestParam("password") String password) {
        StringBuilder result = new StringBuilder();
        try {
            // 安全函数验证
            this.securityValidate(username, password);
 
            Class.forName(driver);
            Connection con = DriverManager.getConnection(url, user, password);
            Statement statement = con.createStatement();
            String sql = "select * from users where username = '" + username + "'";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                String res_name = rs.getString("username");
                String res_pwd = rs.getString("password");
                String info = String.format("%s: %s\n", res_name, res_pwd);
                result.append(info);
            }
            rs.close();
            con.close();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result.toString();
}
 
// 安全验证函数
public void securityValidate(String username, String password) throws Exception {
    Pattern FILTER_PATTERN = Pattern.compile("^[a-zA-Z0-9_/\\.-]+$");
    if (!FILTER_PATTERN.matcher(username).matches()) {
        throw new Exception("用户名格式验证失败");
    }
    if (!FILTER_PATTERN.matcher(password).matches()) {
        throw new Exception("密码格式验证失败");
    }
}